package com.xli.organ.user.frameuser.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xli.dto.component.SelectItem;
import com.xli.dto.component.TreeNode;
import com.xli.dto.component.model.TableModel;
import com.xli.dto.component.model.TreeModel;
import com.xli.dto.controller.BaseController;
import com.xli.dto.params.IdsDTO;
import com.xli.dto.params.TreeNodeDTO;
import com.xli.dto.result.ResultVO;
import com.xli.dto.result.status.Status;
import com.xli.dto.validation.group.IGroup;
import com.xli.mis.codemain.utils.CodeModalFactory;
import com.xli.mybatis.utils.TableUtil;
import com.xli.organ.ou.frameou.entity.FrameOu;
import com.xli.organ.ou.frameou.entity.mapper.IFrameOuMapper;
import com.xli.organ.ou.frameou.entity.vo.OuVO;
import com.xli.organ.ou.frameou.service.IFrameOuService;
import com.xli.organ.user.frameuser.entity.FrameUser;
import com.xli.organ.user.frameuser.entity.dto.UserAddDTO;
import com.xli.organ.user.frameuser.entity.dto.UserSearchDTO;
import com.xli.organ.user.frameuser.entity.dto.UserUpdateDTO;
import com.xli.organ.user.frameuser.entity.mapper.IFrameUserMapper;
import com.xli.organ.user.frameuser.entity.vo.UserVO;
import com.xli.organ.user.frameuser.service.IFrameUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Tag(name = "用户管理")
@RestController
@RequestMapping("/frameUser")
public class FrameUserController extends BaseController {

    @Autowired
    IFrameUserService iFrameUserService;
    @Autowired
    IFrameOuService iFrameOuService;

    @Operation(summary = "保存用户")
    @PostMapping(value = "/add")
    public ResultVO<String> add(@RequestBody @Validated(IGroup.add.class) UserAddDTO dto) throws Exception {
        boolean result = saveIfNotExists(TableUtil.getTableName(FrameUser.class),
                () -> iFrameUserService.findUserByLoginId(dto.getLoginId()) == null,
                () -> iFrameUserService.insert(IFrameUserMapper.INSTANCE.toEntity(dto)),
                String.format("loginId '%s' 已存在", dto.getLoginId()));
        if (result) {
            return new ResultVO<>(Status.SUCCESS, "保存成功");
        }
        return new ResultVO<>(Status.FAILED, "保存失败");
    }

    @Operation(summary = "删除用户")
    @PostMapping(value = "/delete")
    public ResultVO<String> delete(@RequestBody @Validated(IGroup.delete.class) IdsDTO dto) {
        int i = 0;
        for (String id : dto.getIds()) {
            if (iFrameUserService.delete(Long.valueOf(id))) {
                i++;
            }
        }
        return new ResultVO<>(Status.SUCCESS, i + "条数据删除成功");
    }

    @Operation(summary = "更新用户")
    @PostMapping(value = "/update")
    public ResultVO<String> update(@RequestBody @Validated(IGroup.update.class) UserUpdateDTO dto) {
        FrameUser frameUser = IFrameUserMapper.INSTANCE.toEntity(dto);
        if (iFrameUserService.update(frameUser)) {
            return new ResultVO<>(Status.SUCCESS, "更新成功");
        }
        return new ResultVO<>(Status.FAILED, "更新失败");
    }

    @Operation(summary = "查询详情")
    @PostMapping(value = "/detail/{id}")
    public ResultVO<UserVO> detail(@PathVariable("id") String id) {
        FrameUser frameUser = iFrameUserService.find(Long.valueOf(id));
        if (frameUser != null) {
            return new ResultVO<>(Status.SUCCESS, "查询成功", IFrameUserMapper.INSTANCE.toVO(frameUser));
        }
        return new ResultVO<>(Status.FAILED, "查询失败");
    }

    @Operation(summary = "查询列表")
    @PostMapping(value = "/search")
    public ResultVO<TableModel<UserVO, FrameUser, UserSearchDTO>> search(@RequestBody @Validated(IGroup.search.class) UserSearchDTO dto) {

        TableModel<UserVO, FrameUser, UserSearchDTO> tableModel = new TableModel<>(dto) {
            @Override
            public List<UserVO> fetch(int current, int pageSize) {
                Page<FrameUser> page = iFrameUserService.findList(getQueryWrapper(), current, pageSize);
                this.setTotal(page.getTotal());
                return page.convert(IFrameUserMapper.INSTANCE::toVO).getRecords();
            }
        };
        return new ResultVO<>(Status.SUCCESS, "查询成功", tableModel);
    }

    @PostMapping(value = "/fetchOuTree")
    public ResultVO<TreeModel<OuVO>> fetchOuTree(@RequestBody @Validated(IGroup.search.class) Optional<TreeNodeDTO> dto) {

        TreeModel<OuVO> treeModel = new TreeModel<>() {
            @Override
            public List<TreeNode<OuVO>> fetch() {
                List<TreeNode<OuVO>> treeNodeList = new ArrayList<>();
                List<FrameOu> frameOuList = iFrameOuService.findList(new QueryWrapper<>());
                for (FrameOu frameOu : frameOuList) {
                    OuVO ouVO = IFrameOuMapper.INSTANCE.toVO(frameOu);
                    TreeNode<OuVO> childNode = new TreeNode<>();
                    childNode.setId(frameOu.getId());
                    childNode.setText(frameOu.getOu_name());
                    childNode.setPid(frameOu.getPid());
                    treeNodeList.add(childNode);
                }

                return treeNodeList;
            }
        };
        return new ResultVO<>(Status.SUCCESS, "查询成功", treeModel);
    }

    @Operation(summary = "查询性别")
    @PostMapping(value = "/getGenderModel")
    public ResultVO<List<SelectItem>> getGenderModel() {
        List<SelectItem> selectItemList = CodeModalFactory.factory("性别", false);
        return new ResultVO<>(Status.SUCCESS, "查询成功", selectItemList);
    }

    @Operation(summary = "查询账号状态")
    @PostMapping(value = "/getEnabledModel")
    public ResultVO<List<SelectItem>> getEnabledModel() {
        List<SelectItem> selectItemList = CodeModalFactory.factory("账号状态", false);
        return new ResultVO<>(Status.SUCCESS, "查询成功", selectItemList);
    }
}
